package com.zw.pm.module.board.dailyoutputtotal;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.zw.pm.gen.entity.OutputDailyTotal;
import com.zw.pm.gen.entity.OutputDailyTotalExample;
import com.zw.pm.gen.entity.User;
import com.zw.pm.gen.mapper.OutputDailyTotalMapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 日产量总计 服务层
 * @Author: China.wsg
 * @Date: 2020/01/09 08:42
 */
@Service
public class DailyOutputTotalService {

    @Autowired
    private OutputDailyTotalMapper outputDailyTotalMapper1;
    @Value("${user.upload.path}")
    private String uploadPath;
    private String msg = "";


    /**
     * 导入日报
     *
     * @param file      导入文件
     * @param yearMonth 日报所属年月
     * @return
     */
    @Transactional
    public String dailyTotalImport(MultipartFile file, Date yearMonth) {

        try {

            msg = "导入成功";

            // 删除导入月数据
            Calendar ca = Calendar.getInstance();
            ca.setTime(yearMonth);
            Integer yearQuery = ca.get(Calendar.YEAR);
            Integer monthQuery = ca.get(Calendar.MONTH) + 1;

            OutputDailyTotalExample ex = new OutputDailyTotalExample();
            OutputDailyTotalExample.Criteria criteria = ex.createCriteria();
            criteria.andYearEqualTo(yearQuery);
            criteria.andMonthEqualTo(monthQuery);
            outputDailyTotalMapper1.deleteByExample(ex);

            EasyExcel.read(file.getInputStream(), OutputDailyTotal.class, new DailyOutputTotalListener(outputDailyTotalMapper1, yearMonth, uploadPath, dailyOutputTotalModels -> {
                if (dailyOutputTotalModels != null && dailyOutputTotalModels.size() > 0) {
                    msg = "导入失败";

                    // 导出异常Excel
                    exportErrorExcel(dailyOutputTotalModels);
                }
            })).headRowNumber(3).sheet().doRead();

        } catch (IOException e) {
            msg = "导入失败";
            return msg;
        }
        return msg;
    }

    /**
     * 判断文件是否存在
     *
     * @param url 文件URL
     * @return 是否存在
     */
    public boolean exist(String url) {
        int i = url.lastIndexOf("files/");
        String path = uploadPath + url.substring(i + 6);
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }

        return true;
    }

    /**
     * 异常数据导出到Excel
     */
    private void exportErrorExcel(List<DailyOutputTotalModel> errorList) {

        if (errorList.size() <= 0) {
            return;
        }

        User user = (User) SecurityUtils.getSubject().getPrincipal();

        // 取得错误数据
        String path = uploadPath + user.getAccount() + "/";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        path = path + "dailyError.xls";
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);

        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        // 这里 需要指定写用哪个class去读，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        EasyExcel.write(path, DailyOutputTotalModel.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("模板")
                .doWrite(errorList);

    }

}
